﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using  RegexJson.Common;
using System.Text;
using System.Net;
using System.IO;
using System.Text.RegularExpressions;
using System.Web;
namespace RegexJson
{
    public partial class FrmMian : Form
    {
        public FrmMian()
        {
            InitializeComponent();
            AppLog.Init();
            //AppLog.Write("ss", AppLog.LogMessageType.Debug);
        }

        private void toolStripMenuItem1_Click(object sender, EventArgs e)
        {
            HideMainForm();
        }
        #region 双击托盘上图标时，显示窗体
        private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            if (this.WindowState == FormWindowState.Normal)
            {
                this.WindowState = FormWindowState.Minimized;

                HideMainForm();
            }
            else if (this.WindowState == FormWindowState.Minimized)
            {
                ShowMainForm();
            }
        }
        #endregion

        #region 点最小化按钮时，最小化到托盘
        private void frmTLQMain_SizeChanged(object sender, EventArgs e)
        {
            if (this.WindowState == FormWindowState.Minimized)
            {
                HideMainForm();
            }
        }
        #endregion

        #region 窗体关闭时最小化到托盘
        private void frmMain_FormClosing(object sender, FormClosingEventArgs e)
        {
            e.Cancel = true;

            HideMainForm();
        }
        #endregion
        #region 私有方法　处理窗体的　显示　隐藏　关闭(退出)
        private void ExitMainForm()
        {
            this.Close();
        }

        private void HideMainForm()
        {
            this.Hide();
        }

        private void ShowMainForm()
        {
            this.Show();
            this.WindowState = FormWindowState.Normal;
            this.Activate();
        }
        #endregion

        private void toolStripMenuItem2_Click(object sender, EventArgs e)
        {
            ShowMainForm();
        }

        private void toolStripMenuItem3_Click(object sender, EventArgs e)
        {
            ExitMainForm();
        }

        private void FrmMian_Load(object sender, EventArgs e)
        {
            this.FormClosing += new FormClosingEventHandler(frmIsMain_FormClosing);
        }

        private void frmIsMain_FormClosing(object sender, System.Windows.Forms.FormClosingEventArgs e)
        {
            if (MessageBox.Show("确定要关闭吗！", "关闭提示", MessageBoxButtons.OKCancel) == DialogResult.OK)
            {


                System.Environment.Exit(0);
            }
            else
                e.Cancel = true;
        }

        private void BtnRegex_Click(object sender, EventArgs e)
        {
            frmRegex reg = new frmRegex();
            reg.Show();
        }

        private void btnIndex_Click(object sender, EventArgs e)
        {
            frmIndex frmindex = new frmIndex();
            frmindex.Show();
        }

        private void btn_LYQ_Click(object sender, EventArgs e)
        {

            //获取当前IP "showword":\s*"(?'showword'[^"]*)"|"dailypv":\s*"(?'dailypv'[^"]*)"
            string result = GetHttpWeb("http://10.0.0.1/RST_conn_status.htm");
            Regex reg = new Regex("info_get_wanip=\"(?'showword'[^\"]*)\"", RegexOptions.Compiled);
            MatchCollection matchC = reg.Matches(result);
            StringBuilder sb = new StringBuilder();
            foreach (Match mc in matchC)
            {
                sb.AppendLine(mc.Value);
                //, Environment.NewLine)
            }

            PostRequestString("http://10.0.0.1/apply.cgi?/RST_conn_status.htm timestamp=92897314", 16000, 1, Encoding.GetEncoding("utf-8"));
            
            //通过路由切换IP
            GetHttpWeb("http://192.168.0.1/do_cmd.htm?CMD=WAN_CON&GO=info.htm&action=4");

            //显示进度
            char[] progress = { '|', '/', '-', '\\' };
            for (int i = 0; i < 10; i++)
            {
                Console.Write("Changing " + progress[i % 4]);
                Console.Write('\r');
                System.Threading.Thread.Sleep(500);
            }
            Console.WriteLine();

            //显示新的IP
            result = GetHttpWeb("http://192.168.0.1/info.htm");

            Console.Write(result);

            Console.ReadKey(true);
        }


        public static void PostHttpWeb(string uri)
        {
            string postdata = "submit_flag=connect_status&endis_connect=3";
            Encoding myEncoding = Encoding.GetEncoding("utf-8");
            string param = HttpUtility.UrlEncode(postdata, myEncoding);
            //HttpUtility.UrlEncode("值A", myEncoding);
            byte[] bs = Encoding.UTF8.GetBytes(param);
            HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(uri);
            req.Method = "POST";
            req.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.1.4322)";
            req.ContentType = "application/x-www-form-urlencoded;charset=utf-8";
            req.Accept = "*/*";
            req.KeepAlive = true;
            req.Headers["Authorization"] = "Basic YWRtaW46eWFuZzIyNjY0NTI=";
            req.ContentLength = bs.Length;
            //req.Credentials = new NetworkCredential("admin", "yang2266452");//路由的用户名和密码
            Stream reqStream = req.GetRequestStream();
            reqStream.Write(bs, 0, bs.Length);
            reqStream.Close();

            WebResponse myWebResponse = req.GetResponse();
            using (StreamReader sr = new StreamReader(myWebResponse.GetResponseStream(), myEncoding))
            {
                // 返回结果

            }
        }


        /// <summary>
        /// 获取指定远程网页内容
        /// </summary>
        /// <param name="strUrl">所要查找的远程网页地址</param>
        /// <param name="timeout">超时时长设置，一般设置为8000</param>
        /// <param name="enterType">是否输出换行符，0不输出，1输出文本框换行</param>
        /// <param name="EnCodeType">编码方式</param>
        public static string PostRequestString(string strUrl, int timeout, int enterType, Encoding EnCodeType, params string[] Parms)
        {
            string strResult;
            try
            {
                HttpWebRequest myReq = (HttpWebRequest)HttpWebRequest.Create(strUrl);
                //myReq.CachePolicy = noCachePolicy;
                myReq.Method = "POST";
                myReq.KeepAlive = true;
                Uri baseUri = new Uri(strUrl);
                myReq.Timeout = timeout;
                myReq.Headers["Accept-Encoding"] = "gzip,deflate,sdch";
                myReq.Headers["Accept-Language"] = "zh-cn,zh;q=0.5";
                myReq.Headers["Accept-Charset"] = "GB2312,utf-8;q=0.7,*;q=0.7";
                myReq.Headers["Authorization"] = "Basic YWRtaW46eWFuZzIyNjY0NTI=";
                
                myReq.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";

                myReq.Referer = "http://10.0.0.1/RST_conn_status.htm";
                
                myReq.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.110 Safari/537.36";
                myReq.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;//自动解压缩

                string postdata = "submit_flag=connect_status&endis_connect=3";
                Encoding myEncoding = Encoding.GetEncoding("utf-8");
                string param = HttpUtility.UrlEncode(postdata, myEncoding);
                //HttpUtility.UrlEncode("值A", myEncoding);
                byte[] bs = Encoding.UTF8.GetBytes(param);
                myReq.ContentLength = bs.Length;
                //req.Credentials = new NetworkCredential("admin", "yang2266452");//路由的用户名和密码
                using (Stream stream = myReq.GetRequestStream())
                {
                    stream.Write(bs, 0, bs.Length);
                }          
               


                HttpWebResponse HttpWResp = (HttpWebResponse)myReq.GetResponse();

                StringBuilder sb = new StringBuilder(40960);
                try
                {

                    Stream myStream = HttpWResp.GetResponseStream();
                    StreamReader sr = new StreamReader(myStream, EnCodeType);
                    while (!sr.EndOfStream)
                    {
                        sb.Append(sr.ReadLine());
                        if (enterType != 1)
                        {
                            sb.Replace("\r\n", "");
                            sb.Replace("\r", "");
                            sb.Replace("\n", "");
                        }
                    }

                    sr.Close();
                    sr.Dispose();
                    myStream.Close();
                    myStream.Dispose();
                }
                catch (Exception ex)
                {
                    strResult = strUrl + "请求错误：" + ex.Message;
                    throw new Exception(strUrl + "请求错误：" + ex.Message);
                }
                finally
                {
                    HttpWResp.Close();
                }

                strResult = sb.ToString();
            }
            catch (Exception err)
            {
                strResult = strUrl + "请求错误：" + err.Message;
                throw new Exception(strUrl + "请求错误：" + err.Message);

            }
            return strResult;
        }

        //读取网页
        public static string GetHttpWeb(string uri)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
            request.Credentials = new NetworkCredential("admin", "yang2266452");//路由的用户名和密码
            request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
            request.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.2; zh-CN; rv:1.9.2) Gecko/20100115 Firefox/3.6";

            // Get the response.
            HttpWebResponse response;

            try
            {
                response = (HttpWebResponse)request.GetResponse();
            }
            catch (Exception)
            {
                throw;
            }
            // Get the stream containing content returned by the server.
            Stream dataStream = response.GetResponseStream();
            // Open the stream using a StreamReader for easy access.
            StreamReader reader = new StreamReader(dataStream, Encoding.GetEncoding("utf-8"));
            // Read the content.
            string rsp = reader.ReadToEnd();
            // Cleanup the streams and the response.
            reader.Close();
            dataStream.Close();
            response.Close();
            request.Abort();
            return rsp;
        }

    }
}
